package com.zone.gateway.sdk.domain.service;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.zone.gateway.common.response.Result;
import com.zone.gateway.common.response.ResultCode;
import com.zone.gateway.sdk.config.ApiGatewaySdkProperties;
import com.zone.gateway.sdk.domain.model.entity.ApplicationInterfaceEntity;
import com.zone.gateway.sdk.domain.model.entity.ApplicationInterfaceMethodEntity;
import com.zone.gateway.sdk.domain.model.entity.ApplicationSystemEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ApplicationConfigRegisManageService {
    private final Logger logger = LoggerFactory.getLogger(ApplicationConfigRegisManageService.class);

    private final ApiGatewaySdkProperties apiGatewaySdkProperties;

    public ApplicationConfigRegisManageService(ApiGatewaySdkProperties apiGatewaySdkProperties) {
        this.apiGatewaySdkProperties = apiGatewaySdkProperties;
    }

    public void regisApplicationSystem(ApplicationSystemEntity applicationSystem) {
        String resultStr = HttpUtil.createPost(apiGatewaySdkProperties.getGatewayCenterUrl() + "/application/manage/regis_application_system")
                .header("Content-Type", "application/json")
                .body(JSONObject.toJSONString(applicationSystem))
                .execute()
                .body();
        Result<?> result = JSONObject.parseObject(resultStr, Result.class);
        if (!ResultCode.SUCCESS.getCode().equals(result.getCode())) {
            logger.warn("register application system: {} error result: {}", applicationSystem, result);
        }
    }

    public void regisApplicationInterface(ApplicationInterfaceEntity applicationInterface) {
        String resultStr = HttpUtil.createPost(apiGatewaySdkProperties.getGatewayCenterUrl() + "/application/manage/regis_application_interface")
                .header("Content-Type", "application/json")
                .body(JSONObject.toJSONString(applicationInterface))
                .execute()
                .body();

        Result<?> result = JSONObject.parseObject(resultStr, Result.class);
        if (!ResultCode.SUCCESS.getCode().equals(result.getCode())) {
            logger.warn("register interface: {} error result: {}", applicationInterface, result);
        }
    }

    public void regisApplicationMethod(ApplicationInterfaceMethodEntity method) {
        String resultStr = HttpUtil.createPost(apiGatewaySdkProperties.getGatewayCenterUrl() + "/application/manage/regis_application_interface_method")
                .header("Content-Type", "application/json")
                .body(JSONObject.toJSONString(method))
                .execute()
                .body();

        Result<?> result = JSONObject.parseObject(resultStr, Result.class);
        if (!ResultCode.SUCCESS.getCode().equals(result.getCode())) {
            logger.warn("register method: {} error result: {}", method, result);
        }
    }

}
